package com.business.dashboard.controller;

import com.business.dashboard.entity.BusinessPlan;
import com.business.dashboard.entity.User;
import com.business.dashboard.model.UserLoginRequest;
import com.business.dashboard.model.UserRegisterRequest;
import com.business.dashboard.model.UserUpdateRequest;
import com.business.dashboard.service.BusinessPlanService;
import com.business.dashboard.service.UserService;
import com.business.dashboard.utils.JwtUtil;
import com.business.dashboard.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前端用户控制器
 *
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@RestController
@RequestMapping("/api/users")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private BusinessPlanService businessPlanService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public ResultUtil<Map<String, Object>> register(@RequestBody @Valid UserRegisterRequest request) {
        try {
            // 验证确认密码
            if (!request.getPassword().equals(request.getConfirmPassword())) {
                return ResultUtil.error("两次输入的密码不一致");
            }

            // 验证用户协议
            if (request.getAgreeTerms() == null || !request.getAgreeTerms()) {
                return ResultUtil.error("请同意用户协议");
            }

            User user = userService.register(request);

            Map<String, Object> result = new HashMap<>();
            result.put("userId", user.getId());
            result.put("username", user.getUsername());
            result.put("email", user.getEmail());

            return ResultUtil.success("注册成功", result);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return ResultUtil.error("注册失败：" + e.getMessage());
        }
    }

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResultUtil<Map<String, Object>> login(@RequestBody @Valid UserLoginRequest request,
                                                 HttpServletRequest httpRequest) {
        try {
            String token = userService.login(request);
            User user = userService.getUserByUsername(request.getUsername());

            // 更新登录信息
            String clientIp = getClientIpAddress(httpRequest);
            userService.updateLoginInfo(user.getId(), clientIp);

            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("user", buildUserResponse(user));
            result.put("expiresIn", 86400); // 24小时

            return ResultUtil.success("登录成功", result);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return ResultUtil.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/me")
    public ResultUtil<Map<String, Object>> getCurrentUser(HttpServletRequest request) {
        try {
            // 从JWT token中获取用户ID
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }

            // 验证token是否为用户token
            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }

            // 验证token是否过期
            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }

            // 获取用户ID
            String userIdStr = jwtUtil.getUserIdFromToken(token);
            Long userId = Long.valueOf(userIdStr);

            // 获取用户信息
            User user = userService.getUserById(userId);
            if (user == null) {
                return ResultUtil.error(404, "用户不存在");
            }

            // 构建响应数据
            Map<String, Object> userResponse = buildUserResponse(user);
            return ResultUtil.success("获取用户信息成功", userResponse);
            
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return ResultUtil.error(401, "获取用户信息失败：" + e.getMessage());
        }
    }

    /**
     * 从请求中获取Token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return request.getParameter("token");
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/profile")
    public ResultUtil<User> updateProfile(@RequestAttribute("userId") Long userId,
                                         @RequestBody @Valid UserUpdateRequest request) {
        try {
            User user = userService.updateUser(userId, request);
            // 清除敏感信息
            user.setPassword(null);
            user.setSalt(null);
            return ResultUtil.success("更新成功", user);
        } catch (Exception e) {
            log.error("更新用户信息失败，userId: {}", userId, e);
            return ResultUtil.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 上传用户头像
     */
    @PostMapping("/avatar")
    public ResultUtil<Map<String, String>> uploadAvatar(@RequestAttribute("userId") Long userId,
                                                        @RequestParam("file") MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return ResultUtil.error("请选择要上传的文件");
            }

            if (file.getSize() > 5 * 1024 * 1024) { // 5MB
                return ResultUtil.error("文件大小不能超过5MB");
            }

            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return ResultUtil.error("只能上传图片文件");
            }

            // TODO: 实现文件上传逻辑
            String avatarUrl = "http://example.com/uploads/avatars/" + userId + ".jpg";

            userService.updateUserAvatar(userId, avatarUrl);

            Map<String, String> result = new HashMap<>();
            result.put("avatarUrl", avatarUrl);

            return ResultUtil.success("上传成功", result);
        } catch (Exception e) {
            log.error("上传头像失败，userId: {}", userId, e);
            return ResultUtil.error("上传失败：" + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PutMapping("/password")
    public ResultUtil<String> changePassword(@RequestAttribute("userId") Long userId,
                                          @RequestBody Map<String, String> request) {
        try {
            String oldPassword = request.get("oldPassword");
            String newPassword = request.get("newPassword");

            if (oldPassword == null || oldPassword.trim().isEmpty()) {
                return ResultUtil.error("原密码不能为空");
            }

            if (newPassword == null || newPassword.trim().isEmpty()) {
                return ResultUtil.error("新密码不能为空");
            }

            if (newPassword.length() < 6) {
                return ResultUtil.error("新密码长度不能少于6位");
            }

            boolean success = userService.changePassword(userId, oldPassword, newPassword);
            if (success) {
                return ResultUtil.success("密码修改成功");
            } else {
                return ResultUtil.error("原密码错误");
            }
        } catch (Exception e) {
            log.error("修改密码失败，userId: {}", userId, e);
            return ResultUtil.error("修改密码失败：" + e.getMessage());
        }
    }

    /**
     * 关注用户
     */
    @PostMapping("/{id}/follow")
    public ResultUtil<String> followUser(@RequestAttribute("userId") Long followerId,
                                      @PathVariable @NotNull Long id) {
        try {
            if (followerId.equals(id)) {
                return ResultUtil.error("不能关注自己");
            }

            boolean success = userService.followUser(followerId, id);
            if (success) {
                return ResultUtil.success("关注成功");
            } else {
                return ResultUtil.error("关注失败");
            }
        } catch (Exception e) {
            log.error("关注用户失败，followerId: {}, followedId: {}", followerId, id, e);
            return ResultUtil.error("关注失败：" + e.getMessage());
        }
    }

    /**
     * 取消关注
     */
    @DeleteMapping("/{id}/follow")
    public ResultUtil<String> unfollowUser(@RequestAttribute("userId") Long followerId,
                                        @PathVariable @NotNull Long id) {
        try {
            boolean success = userService.unfollowUser(followerId, id);
            if (success) {
                return ResultUtil.success("取消关注成功");
            } else {
                return ResultUtil.error("取消关注失败");
            }
        } catch (Exception e) {
            log.error("取消关注失败，followerId: {}, followedId: {}", followerId, id, e);
            return ResultUtil.error("取消关注失败：" + e.getMessage());
        }
    }

    /**
     * 获取关注列表
     */
    @GetMapping("/{id}/following")
    public ResultUtil<List<User>> getFollowingList(@PathVariable @NotNull Long id,
                                                   @RequestParam(defaultValue = "1") Integer page,
                                                   @RequestParam(defaultValue = "10") Integer size) {
        try {
            List<User> followingList = userService.getFollowingList(id, page, size);
            return ResultUtil.success("获取成功", followingList);
        } catch (Exception e) {
            log.error("获取关注列表失败，userId: {}", id, e);
            return ResultUtil.error("获取关注列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取粉丝列表
     */
    @GetMapping("/{id}/followers")
    public ResultUtil<List<User>> getFollowersList(@PathVariable @NotNull Long id,
                                                   @RequestParam(defaultValue = "1") Integer page,
                                                   @RequestParam(defaultValue = "10") Integer size) {
        try {
            List<User> followersList = userService.getFollowersList(id, page, size);
            return ResultUtil.success("获取成功", followersList);
        } catch (Exception e) {
            log.error("获取粉丝列表失败，userId: {}", id, e);
            return ResultUtil.error("获取粉丝列表失败：" + e.getMessage());
        }
    }

    /**
     * 检查用户名是否可用
     */
    @GetMapping("/check-username")
    public ResultUtil<Map<String, Boolean>> checkUsername(@RequestParam String username) {
        try {
            boolean exists = userService.existsByUsername(username);
            Map<String, Boolean> result = new HashMap<>();
            result.put("available", !exists);
            return ResultUtil.success("检查完成", result);
        } catch (Exception e) {
            log.error("检查用户名失败，username: {}", username, e);
            return ResultUtil.error("检查失败：" + e.getMessage());
        }
    }

    /**
     * 检查邮箱是否可用
     */
    @GetMapping("/check-email")
    public ResultUtil<Map<String, Boolean>> checkEmail(@RequestParam String email) {
        try {
            boolean exists = userService.existsByEmail(email);
            Map<String, Boolean> result = new HashMap<>();
            result.put("available", !exists);
            return ResultUtil.success("检查完成", result);
        } catch (Exception e) {
            log.error("检查邮箱失败，email: {}", email, e);
            return ResultUtil.error("检查失败：" + e.getMessage());
        }
    }

    /**
     * 获取客户端IP地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            return xForwardedFor.split(",")[0];
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        return request.getRemoteAddr();
    }

    /**
     * 构建用户响应对象
     */
    private Map<String, Object> buildUserResponse(User user) {
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("id", user.getId());
        userMap.put("username", user.getUsername());
        userMap.put("email", user.getEmail());
        userMap.put("name", user.getName());
        userMap.put("nickname", user.getNickname());
        userMap.put("avatar", user.getAvatar());
        userMap.put("company", user.getCompany());
        userMap.put("industry", user.getIndustry());
        userMap.put("position", user.getPosition());
        userMap.put("location", user.getLocation());
        userMap.put("vipLevel", user.getVipLevel());
        userMap.put("verificationStatus", user.getVerificationStatus());
        return userMap;
    }

    // ===== 商业计划书相关接口 =====

    /**
     * 创建商业计划书
     */
    @PostMapping("/business-plans")
    public ResultUtil<BusinessPlan> createBusinessPlan(HttpServletRequest request,
                                                       @RequestBody Map<String, Object> planData) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }
            
            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }
            
            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }
            
            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));
            
            BusinessPlan businessPlan = new BusinessPlan();
            businessPlan.setUserId(userId);
            businessPlan.setTitle((String) planData.get("title"));
            businessPlan.setCompanyName((String) planData.get("companyName"));
            businessPlan.setIndustry((String) planData.get("industry"));
            businessPlan.setBusinessModel((String) planData.get("businessModel"));
            businessPlan.setTargetMarket((String) planData.get("targetMarket"));
            businessPlan.setProblemStatement((String) planData.get("problemStatement"));
            businessPlan.setSolution((String) planData.get("solution"));
            businessPlan.setPlanData(planData.toString());
            businessPlan.setStatus("draft");

            BusinessPlan createdPlan = businessPlanService.createPlan(businessPlan);
            return ResultUtil.success("创建业务计划成功", createdPlan);
        } catch (Exception e) {
            log.error("创建业务计划失败", e);
            return ResultUtil.error("创建业务计划失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户的商业计划书列表
     */
    @GetMapping("/business-plans")
    public ResultUtil<List<BusinessPlan>> getUserBusinessPlans(HttpServletRequest request,
                                                              @RequestParam(defaultValue = "1") Integer page,
                                                              @RequestParam(defaultValue = "10") Integer size) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null || token.isEmpty()) {
                return ResultUtil.error(401, "未登录或token无效");
            }
            
            if (!jwtUtil.isUserToken(token)) {
                return ResultUtil.error(401, "无效的用户token");
            }
            
            if (jwtUtil.isTokenExpired(token)) {
                return ResultUtil.error(401, "token已过期，请重新登录");
            }
            
            Long userId = Long.valueOf(jwtUtil.getUserIdFromToken(token));
            
            List<BusinessPlan> plans = businessPlanService.getUserPlans(userId, page, size);
            return ResultUtil.success("获取业务计划列表成功", plans);
        } catch (Exception e) {
            log.error("获取业务计划列表失败", e);
            return ResultUtil.error("获取业务计划列表失败：" + e.getMessage());
        }
    }

    /**
     * 获取商业计划书模板（公开接口，无需登录）
     */
    @GetMapping("/business-plans/templates")
    public ResultUtil<List<Map<String, Object>>> getBusinessPlanTemplates() {
        try {
            List<Map<String, Object>> templates = new ArrayList<>();
            
            Map<String, Object> techTemplate = new HashMap<>();
            techTemplate.put("id", "tech_startup");
            techTemplate.put("name", "科技创业模板");
            techTemplate.put("description", "适用于科技类创业项目的商业计划书模板");
            techTemplate.put("industry", "科技");
            templates.add(techTemplate);
            
            Map<String, Object> retailTemplate = new HashMap<>();
            retailTemplate.put("id", "retail_business");
            retailTemplate.put("name", "零售业务模板");
            retailTemplate.put("description", "适用于零售行业的商业计划书模板");
            retailTemplate.put("industry", "零售");
            templates.add(retailTemplate);
            
            Map<String, Object> serviceTemplate = new HashMap<>();
            serviceTemplate.put("id", "service_business");
            serviceTemplate.put("name", "服务业务模板");
            serviceTemplate.put("description", "适用于服务行业的商业计划书模板");
            serviceTemplate.put("industry", "服务");
            templates.add(serviceTemplate);
            
            return ResultUtil.success("获取模板成功", templates);
        } catch (Exception e) {
            log.error("获取业务计划模板失败", e);
            return ResultUtil.error("获取模板失败：" + e.getMessage());
        }
    }

}